package com.imut.lagain.controller;

import com.imut.lagain.entity.User;
import com.imut.lagain.service.IUserService;
import com.imut.lagain.service.IWeChatService;
import com.imut.lagain.util.JwtUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    private final IWeChatService weChatService;
    private final IUserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 微信登录
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/wx-login")
    public ResponseEntity<Map<String, Object>> wxLogin(@Valid @RequestBody WxLoginRequest loginRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            log.info("1. 通过code获取session信息");
            Map<String, String> sessionInfo = weChatService.getSessionInfo(loginRequest.getCode());
            if (sessionInfo == null) {
                response.put("success", false);
                response.put("message", "获取微信session失败");
                return ResponseEntity.badRequest().body(response);
            }
            
            String openid = sessionInfo.get("openid");
            String sessionKey = sessionInfo.get("session_key");
            
            log.info("2. 查找或创建用户");
            User user = userService.getOrCreateUser(openid, null, loginRequest.getNickname(), loginRequest.getAvatarUrl(), null);
            
            log.info("4. 生成JWT令牌");
            String token = jwtUtil.generateToken(user.getId(), user.getOpenid());
            
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("user", user);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("微信登录失败", e);
            response.put("success", false);
            response.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 验证Token
     * @param token JWT令牌
     * @return 验证结果
     */
    @PostMapping("/verify-token")
    public ResponseEntity<Map<String, Object>> verifyToken(@NotBlank(message = "Token不能为空") @RequestParam String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (jwtUtil.validateToken(token)) {
                Long userId = jwtUtil.getUserIdFromToken(token);
                User user = userService.getById(userId);
                
                if (user != null) {
                    response.put("success", true);
                    response.put("message", "Token验证成功");
                    response.put("user", user);
                    return ResponseEntity.ok(response);
                } else {
                    response.put("success", false);
                    response.put("message", "用户不存在");
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
                }
            } else {
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
        } catch (Exception e) {
            log.error("Token验证失败", e);
            response.put("success", false);
            response.put("message", "Token验证失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 微信登录请求DTO
     */
    public static class WxLoginRequest {
        @NotBlank(message = "微信授权码不能为空")
        private String code;
        
        @NotBlank(message = "加密数据不能为空")
        private String encryptedData;
        
        @NotBlank(message = "初始向量不能为空")
        private String iv;
        
        @Size(min = 1, max = 50, message = "昵称长度必须在1-50之间")
        private String nickname;
        
        @Pattern(regexp = "^https?://.*\\.(jpg|jpeg|png|gif|webp)$", message = "头像URL格式不正确")
        private String avatarUrl;
        
        public String getCode() {
            return code;
        }
        
        public void setCode(String code) {
            this.code = code;
        }
        
        public String getEncryptedData() {
            return encryptedData;
        }
        
        public void setEncryptedData(String encryptedData) {
            this.encryptedData = encryptedData;
        }
        
        public String getIv() {
            return iv;
        }
        
        public void setIv(String iv) {
            this.iv = iv;
        }
        
        public String getNickname() {
            return nickname;
        }
        
        public void setNickname(String nickname) {
            this.nickname = nickname;
        }
        
        public String getAvatarUrl() {
            return avatarUrl;
        }
        
        public void setAvatarUrl(String avatarUrl) {
            this.avatarUrl = avatarUrl;
        }
    }
}